import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { app, shell, BrowserWindow, ipcMain, dialog } from 'electron'
import icon from '../../build/icon.png?asset'
import { FfmpegService } from './ffmpeg'
import * as fs from 'fs'

const ffmpegService = new FfmpegService()

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron.panomic-video-tool')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // FFMpeg相关IPC处理
  ipcMain.handle('ffmpeg:convert-to-m3u8', async (_, inputFile: string, outputDir: string) => {
    try {
      await ffmpegService.convertToM3U8(inputFile, outputDir, (log) => {
        // 发送日志到渲染进程
        BrowserWindow.getAllWindows()[0]?.webContents.send('ffmpeg:log', log)
      })
      return { success: true }
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '未知错误' }
    }
  })

  ipcMain.handle('ffmpeg:check-availability', async () => {
    return await ffmpegService.checkFfmpeg()
  })

  ipcMain.handle('ffmpeg:extract-panorama-frames', async (_, inputFile: string, outputDir: string, interval?: number, resolution?: string) => {
    try {
      await ffmpegService.extractPanoramaFrames(inputFile, outputDir, interval || 0.5, resolution || '1920x1080', (log) => {
        // 发送日志到渲染进程
        BrowserWindow.getAllWindows()[0]?.webContents.send('ffmpeg:log', log)
      })
      return { success: true }
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '未知错误' }
    }
  })

  ipcMain.handle('ffmpeg:extract-panorama-projections', async (_, inputFile: string, outputDir: string, interval?: number, projectionType?: '5views' | '8views', resolution?: string) => {
    try {
      await ffmpegService.extractPanoramaProjections(inputFile, outputDir, interval || 0.5, projectionType || '5views', resolution || '1920x1080', (log) => {
        // 发送日志到渲染进程
        BrowserWindow.getAllWindows()[0]?.webContents.send('ffmpeg:log', log)
      })
      return { success: true }
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '未知错误' }
    }
  })

  // 全景照片透视图提取
  ipcMain.handle('ffmpeg:extract-panorama-photo-projections', async (_, inputDir: string, outputDir: string, projectionType: '5views' | '8views', resolution?: string) => {
    try {
      await ffmpegService.extractPanoramaPhotoProjections(inputDir, outputDir, projectionType, resolution || '1920x1080', (log) => {
        // 发送日志到渲染进程
        BrowserWindow.getAllWindows()[0]?.webContents.send('ffmpeg:log', log)
      })
      return { success: true }
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '未知错误' }
    }
  })
  // 添加文件系统API处理
  ipcMain.handle('fs:exists-sync', async (_, filePath: string) => {
    return fs.existsSync(filePath)
  })

  ipcMain.handle('fs:read-file', async (_, filePath: string) => {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  })

  // 添加对话框API处理
  ipcMain.handle('dialog:show-open-dialog', async (_, options: any) => {
    return dialog.showOpenDialog(options)
  })

  // 打开文件对话框
  ipcMain.handle('dialog:open-file', async (_, options: any) => {
    const result = await dialog.showOpenDialog({
      ...options,
      properties: ['openFile'],
      title: '选择文件'
    })
    return result.canceled ? null : result.filePaths[0]
  })

  // 打开目录对话框
  ipcMain.handle('dialog:open-directory', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory'],
      title: '选择目录'
    })
    return result.canceled ? null : result.filePaths[0]
  })
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// 打开关于窗口
ipcMain.handle('window:open-about', async () => {
  const aboutWindow = new BrowserWindow({
    width: 440,
    height: 360,
    title: '关于全景视频提取工具',
    modal: false,
    resizable: false,
    maximizable: false,
    minimizable: false,
    parent: BrowserWindow.getAllWindows()[0],
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  aboutWindow.setMenuBarVisibility(false)

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    aboutWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#/about`)
  } else {
    aboutWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: '/about' })
  }

  return { success: true }
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})